from os import environ
from flask import Flask
from flask import render_template,request

import os
os.environ["CPU_NUM"]='8'
from time import *
import paddlex as pdx
import cv2

app = Flask(__name__)
app.jinja_env.variable_start_string = '{['
app.jinja_env.variable_end_string = ']}'

model = None

@app.route('/', methods=("GET", "POST"))
def hello_world():
    global model
    url=''
    url2=''
    deleteImg()
    if request.method == "POST":
        tupian = request.files.get('myFiles')
        if tupian != None:
            print(tupian.filename)
            url='static/images/'+tupian.filename
            tupian.save(url)
            result = model.predict(url)
            pdx.det.visualize(url, result, threshold=0.5, save_dir='static/images/')
            url2= 'static/images/visualize_'+ tupian.filename
    print(url)
    return render_template(
        'index.html',
		 title = url ,
		 readimg=url2
    )

def deleteImg():
	global logger
	try:
		baseUrl='static/images/'
		list = os.listdir(baseUrl)
		for i in range(0, len(list)):
			path = baseUrl + list[i];
			os.remove(path)
	except Exception as e:
		print('deleteImgs出现异常:' + str(e))
		return None

def main():
    global model
    print("Loading model...")
    model = pdx.deploy.Predictor('inference_model_m6', use_gpu=False)
    print("Model loaded.")
    

if __name__ == '__main__':
    main()

    HOST = environ.get('SERVER_HOST', '0.0.0.0')
    try:
        PORT = int(environ.get('SERVER_PORT', '5002'))
    except ValueError:
        PORT = 5002
    app.run(HOST, PORT)
	#app.run(debug=True, host='0.0.0.0', port=5000)

